const withTimeoutRetry = ({ fn, timeout = 3000, retryTimes = 1, hint = '' } = {}) => {
  return new Promise(resolve => {
    let retriesLeft = retryTimes
    let currTimeout
    let done = false
    const exec = () => {
      if (retryTimes > 0) {
        currTimeout = setTimeout(() => {
          if (!done) {
            if (retriesLeft > 0) {
              console.log(`${hint ? hint : ''}重试第 ${retryTimes - retriesLeft + 1} 次...`)
              retriesLeft--
              exec()
              return
            } else {
              console.log(`${retryTimes} 次重试失败！`)
              resolve()
            }
          }
        }, timeout)
      }
      fn().then(res => {
        done = true
        clearTimeout(currTimeout)
        resolve(res)
      })
    }
    exec()
  })
}

exports.withTimeoutRetry = withTimeoutRetry

const wait = t => new Promise(resolve => {
  setTimeout(() => {
    resolve()
  }, t)
})

exports.wait = wait
